package com.purong.purong.activity;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;


import com.purong.purong.PermissionConstant;
import com.purong.purong.R;
import com.purong.purong.util.CommonUtil;
import com.yao.sdk.encrypt.MD5;
import com.yao.sdk.net.ResponseInfo;

import java.util.LinkedHashMap;
import java.util.Map;


/**
 * Created by Administrator on 2016/7/22.
 */
@SuppressLint("SetJavaScriptEnabled")
public class WebActivity extends BasePermActivity {
    private WebView mWebView;
    private String url, title;
    private boolean titleBar, addDId;
    private ProgressBar progressBar;

    @Override
    public void initBundle() {
        url = getIntent().getStringExtra("URL");
        title = getIntent().getStringExtra("TITLE");
        titleBar = getIntent().getBooleanExtra("TITLEBAR", false);
        addDId = getIntent().getBooleanExtra("DEVICE_ID", false);
    }

    @Override
    public int getRootViewId() {
        return R.layout.activity_web;
    }

    @Override
    protected String[] getPermissions() {

        return PermissionConstant.PERMS_PHONE_STATE;
    }

    @Override
    protected void doPermissinosSuc() {
        if (addDId) {
            url = url + "?did=" + MD5.getMD5Str(CommonUtil.getIMEI(this));
        }
        mWebView.loadUrl(url);
    }

    @Override
    protected void onResume() {
        super.onResume();
//        if (mWebView!=null)
//            mWebView.reload();
    }

    public void initView() {
        showBack();
        if (title != null) {
            showTitle(title);
        }
        if (!titleBar) {
            findViewById(R.id.top_view).setVisibility(View.GONE);
        }
        progressBar=(ProgressBar)findViewById(R.id.progress_bar);
        mWebView = (WebView) findViewById(R.id.web_view);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.getSettings().setBuiltInZoomControls(true);
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setDisplayZoomControls(false);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setAppCacheEnabled(true);// 是否使用缓存
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setTextZoom(100);
        mWebView.getSettings().setBlockNetworkImage(false); // 解决图片不显示
        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            mWebView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        mWebView.setWebViewClient(new WebViewClient() {

            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
//                super.onReceivedHttpError(view, request, errorResponse);
                Log.e("zwj", ".....onReceivedHttpError");
//                findViewById(R.id.reload_lay).setVisibility(View.VISIBLE);
//                findViewById(R.id.top_view).setVisibility(View.VISIBLE);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                // 获取上下文, H5PayDemoActivity为当前页面

                // ------  对alipays:相关的scheme处理 -------
                if (url.startsWith("alipays:") || url.startsWith("alipay")) {
                    try {
                        startActivity(new Intent("android.intent.action.VIEW", Uri.parse(url)));
                    } catch (Exception e) {

                    }
                    return true;
                }
                if (url.startsWith("weixin://wap/pay?")) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setData(Uri.parse(url));
                    startActivity(intent);

                    return true;
                }
                // ------- 处理结束 -------

                if (!(url.startsWith("http") || url.startsWith("https"))) {
                    return true;
                }

//                view.loadUrl(url);
                return false;
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                progressBar.setVisibility(View.INVISIBLE);
                Log.e("zwj", ".....onPageFinished");
            }
            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                    return;
                }
                // 在这里显示自定义错误页
                findViewById(R.id.reload_lay).setVisibility(View.VISIBLE);
                findViewById(R.id.top_view).setVisibility(View.VISIBLE);
            }

            // 新版本，只会在Android6及以上调用
            @TargetApi(Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                super.onReceivedError(view, request, error);
                if (request.isForMainFrame()){ // 或者： if(request.getUrl().toString() .equals(getUrl()))
                    // 在这里显示自定义错误页
                    findViewById(R.id.reload_lay).setVisibility(View.VISIBLE);
                    findViewById(R.id.top_view).setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
//                super.onReceivedSslError(view, handler, error);
                Log.e("zwj", ".....onReceivedSslError");
//                findViewById(R.id.reload_lay).setVisibility(View.VISIBLE);
            }
        });
        mWebView.setWebChromeClient(new WebChromeClient(){
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                // TODO 自动生成的方法存根

                if(newProgress==100){
                    progressBar.setVisibility(View.INVISIBLE);//加载完网页进度条消失
                }
                else{
                    progressBar.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                    progressBar.setProgress(newProgress);//设置进度值
                }

            }
        });

    }

    @Override
    public void initData() {
        if (url != null) {
            if (Build.VERSION.SDK_INT >= 23 && addDId) {
                checkPermission();
            } else {
                if (addDId) {
                    url = url + "?did=" + MD5.getMD5Str(CommonUtil.getIMEI(this));
                }
                mWebView.loadUrl(url);
            }

        }
    }

    public void onReLoad(View v) {
        if (mWebView != null) {
            mWebView.reload();
            findViewById(R.id.reload_lay).setVisibility(View.GONE);
            if (!titleBar) {
                findViewById(R.id.top_view).setVisibility(View.GONE);
            }
        }

    }


}
